/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aiaudio.lastfm;

import aiaudio.lastfm.hbase.SchemeCommunicator;
import de.umass.lastfm.User;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author nastya
 */
public class UserByIdExtracter {

    private final SchemeCommunicator communicator;
    private final int fromId;
    private final int toId;
    
    private int lastId;

    public int getLastId() {
        return lastId;
    }
    

    public UserByIdExtracter(SchemeCommunicator communicator, int fromId, int toId) {
        this.communicator = communicator;
        this.fromId = fromId;
        lastId = fromId;
        this.toId = toId;
    }

    public void start() throws IOException {
        for (int i = fromId; i <= toId; i++) {
            tryAddUser(i);
        }
    }

    protected void tryAddUser(int i) throws IOException {        
        User u = User.getInfo(i + "", LastFmDownloaderHBase.API_KEY);
        printProgress(i);
        if(u == null || u.getPlaycount() < 100){
            return;
        }
        communicator.insertUser(u);
        
        lastId = Integer.parseInt(u.getId());
    }

    private void printProgress(int i) {
        Date now = Calendar.getInstance().getTime();
        String formatted = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now);
        if(i % 100 == 0){
            System.out.println(formatted + " get " + i + " from " + toId);
        }
    }
}
